package tools.project.controller {
	import flash.events.Event;
	import flash.filesystem.File;

	import kiwi.action.queue.Queue;
	import kiwi.debug.Log;
	import kiwi.event.ActionEvent;
	import kiwi.util.ArrayUtils;
	import kiwi.util.sprintf;

	import org.aswing.JOptionPane;
	import org.robotlegs.mvcs.Command;

	import tools.event.ProjectEvent;
	import tools.model.ActionInfo;
	import tools.model.EditorConfig;
	import tools.model.FrameInfo;
	import tools.model.TileInfo;
	import tools.project.controller.action.SavePNGAction;
	import tools.project.controller.action.SavePackageAction;
	import tools.project.controller.action.SaveSmallXmlAction;
	import tools.project.controller.action.SaveXMLAction;

	/**
	 * 发布项目
	 * @author zhangming.luo
	 */
	public class PublishProjectCommand extends Command {
		[Inject]
		public var config : EditorConfig;
		[Inject]
		public var event : ProjectEvent;
		private var dir : File;
		private var queue : Queue;
		private var quality : Number;

		override public function execute() : void {
			dispatch(new ProjectEvent(ProjectEvent.SAVE, false, false, config.currentName, true));
			if (!event.ignorInfo) {
				JOptionPane.showInputDialog("发布", "发布的品质(默认80%)", onCheckQuality, "80%");
			} else {
				onCheckQuality(event.model);
			}
		}

		private function onCheckQuality(input : String) : void {
			if (!input) {
				return;
			}
			quality = Math.min(Math.max(1, int(input.replace("%", ""))), 100);
			if (config.projectDir) {
				dir = config.projectDir;
				startPublish();
			} else {
				dir = File.desktopDirectory;
				dir.addEventListener(Event.SELECT, function() : void {
					startPublish();
				});
				dir.browseForDirectory("发布到");
			}
		}

		private function startPublish() : void {
			queue = new Queue(null);
			// 保存素材图片
			queue.submit(new SavePNGAction(dir.nativePath + "/" + config.projectName + ".png", config.texture.bitmapData));
			// 保存素材的Tile
			// queue.submit(new SaveTilesAction(dir.nativePath + "/.tiles", config.allTileList));
			// 保存素材的Frame
			// queue.submit(new SaveFramesAction(dir.nativePath + "/.frames", config.allFrameList));
			// 保存素材的Action
			// queue.submit(new SaveActionAction(dir.nativePath + "/.action", config.actionList));
			// 保存sprite的配置
			queue.submit(new SaveXMLAction(dir.nativePath + "/" + config.projectName + ".xml", genericConfigXML()));

			// 保存分割的config.xml
			queue.submit(new SaveSmallXmlAction(dir.nativePath, config));
			//

			// 保存发布的文件
			queue.submit(new SavePackageAction(dir.nativePath, config, quality));
			queue.addEventListener(ActionEvent.ACTION_COMPLETE, onComplete);
			queue.execute();
		}

		/**
		 * 仅仅保留tile,frame,action中关于位置尺寸以及id的信息
		 * <config>
		 * 	<tiles>
		 * 		<tile>
		 * 			<id></id>
		 * 			<source>
		 *				<x></x>
		 * 				<y></y>
		 * 				<width></width>
		 * 				<height></height>
		 * 			</source>
		 * 			<registration>
		 * 				<x></x>
		 * 				<y></y>
		 * 			</registration>
		 * 		</tile>
		 * 	</tiles>
		 * 	<frames>
		 * 		<frame>
		 * 			<id></id>
		 *			<tile>1,2,3,4,5</tile>
		 * 		</frame>
		 * 	</frames>
		 * 	<actions>
		 * 		<action>
		 * 			<name></name>
		 *			<frame>1,2,3,4,5</frame>
		 * 		</action>
		 * 	</actions>
		 * </config>
		 */
		private function genericConfigXML() : XML {
			var result : XML = <config></config>;
			// tiles部分
			var tiles : XML = <tiles></tiles>;
			for each (var tile:TileInfo in config.allTileList) {
				tiles.appendChild(createXMLByObject("tile", {id:tile.id, source:{x:tile.source.x, y:tile.source.y, width:tile.source.width, height:tile.source.height}, registration:{x:tile.registration.x, y:tile.registration.y}}));
			}
			// frame部分
			var frames : XML = <frames></frames>;
			for each (var frame:FrameInfo in config.allFrameList) {
				frames.appendChild(createXMLByObject("frame", {id:frame.id, tile:ArrayUtils.collect(frame.tileList, "id").join(",")}));
			}
			// action部分
			var actions : XML = <actions></actions>;
			for each (var action:ActionInfo in config.actionList) {
				actions.appendChild(createXMLByObject("action", {scale:action.scale, name:action.name, frame_duration:ArrayUtils.collect(action.frameList, "duration").join(","), frame:ArrayUtils.collect(ArrayUtils.collect(action.frameList, "frame"), "id").join(",")}));
			}
			result.appendChild(tiles);
			result.appendChild(frames);
			result.appendChild(actions);
			return result;
		}

		private function createXMLByObject(title : String, obj : *) : XML {
			if (obj is int || obj is Number || obj is String || obj is Boolean || obj is uint) {
				return new XML(sprintf("<%s>%s</%s>", title, obj, title));
			}
			var xml : XML = new XML(sprintf("<%s></%s>", title, title));
			for (var key:String in obj) {
				var subXML : XML;
				if (obj[key] is Array) {
					subXML = new XML(sprintf("<%s></%s>", key, key));
					for each (var subObj:* in obj[key]) {
						subXML.appendChild(createXMLByObject("item", subObj));
					}
				} else {
					subXML = createXMLByObject(key, obj[key]);
				}
				xml.appendChild(subXML);
			}
			return xml;
		}

		private function onComplete(event : ActionEvent) : void {
			if (!this.event.ignorInfo) {
				Log.alert("发布完毕");
			}
			dispatch(new ProjectEvent(ProjectEvent.PUBLISH_COMPLETE));
		}
	}
}

